import React from "react";
import GamePad from "./appComponents/GamePad";
import CreateGameBase from "./appComponents/CreateGameBase";
import { NavLink } from "react-router-dom";
import { connect } from "react-redux";
import NumberPad from "./appComponents/NumberPad";
import classnames from "classnames";
import JoinRuleDialog from "./JoinRuleDialog";
import GameConfig from "../reducers/gameconfig";
import "./appStyle.less";

//将state.counter绑定到props的counter
const mapStateToProps = state => {
  return {
    userInfo: state.app.userInfo,
    userFinanceInfo: state.app.userFinanceInfo,
    agentLevel: state.app.agentLevel,
    showCreateGame: state.dynamics.showCreateGame,
    currentGame: state.dynamics.currentGame,
    gameData: state.app.gameData,
    crowdJoin: state.app.crowdJoin,
    clubUrl: state.app.clubUrl,
    hallPage: state.app.hallPage
  };
};
//将action的所有方法绑定到props上
const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    openModal: msg => dispatch(global.allActions.appActions.openModal(msg))
    // increment: (...args) => dispatch(actions.increment(...args)),
    // decrement: (...args) => dispatch(actions.decrement(...args))
  };
};

class App extends React.Component<any, any> {
  public constructor(props) {
    super(props);
    this.state = {
      showNumberPad: false,
      shuaishuaiCname: classnames({
        pulse: false
      }),
      showJoinRule: false,
      showHomeJoin: false,
      clubMethod: "",
      isAndroid: false,
      userAmount: 0,
      showAmount: false
    };
  }

  public componentDidMount() {
    // this.setState({ cluburl: `${config.pre}/login/weiXin/${Cookies.get('areaCode')}?type=10106` })
    setTimeout(() => {
      let shuaishuaiCname = classnames({
        pulse: true
      });
      this.setState({ shuaishuaiCname });
    }, 1000);

    if (window.navigator) {
      // console.error(window.navigator.appVersion.match(/Android/i))
      if (window.navigator.appVersion.match(/Android/i)) {
        this.setState({
          isAndroid: true
        });
      }
    }

    let _this = this;

    // 每3s请求一次
    // body...
    if (
      !window.location.hostname.match(/(10\.10\.10)|(192\.168)|(localhost)/)
    ) {
      let intervalInfoId = setInterval(function(argument) {
        const url = `${config.pre}/personalCenter/info/${Cookies.get(
          "areaCode"
        )}`;
        const opt = { method: "GET" };
        fetchJson(url, opt).then(data => {
          // console.error(data)
          if (data.result === 0) {
            _this.setState({
              userAmount: data.data.humanUser.amount,
              showAmount: true
            });
          }
        });
      }, 3000);
    }

    new Swiper(".room-swiper-container", {
      // Optional parameters
      direction: "horizontal",
      loop: false
    });
    util.resetFontSize();

    console.warn("app did mount");

    let qsStr = queryString.parse(window.location.href);

    let errorCode = qsStr.errorCode;
    let sessionCode = sessionStorage.getItem("errorCode");
    let clubDCode = sessionStorage.getItem("clubdetails");
    let clubCCode = sessionStorage.getItem("clubcreate");
    let type = qsStr.type;
    let to = qsStr.to;

    if(to && clubCCode !== "clubcreate") {
      if (to.match("clubcreate")) {
        sessionStorage.setItem("clubcreate", "clubcreate");
        setTimeout(()=>{
          window.location.hash = '#/Club';
        }, 100);
      }
    }

    if (to && clubDCode !== "clubdetails") {
      if (to.match("clubdetails")) {
        sessionStorage.setItem("clubdetails", "clubdetails");
        setTimeout(()=>{
          window.location.hash = '#/ClubDetails';
        }, 100);
      }
    }

    if (errorCode && sessionCode !== "110") {
      if (errorCode.match("110")) {
        sessionStorage.setItem("errorCode", "110");
        this.props.openModal("房间已解散");
      }
    }

    // window.addEventListener('resize', function (ev) {
    //   let pad = document.querySelectorAll('.home-gamepad') as NodeListOf<HTMLElement>;
    //   pad[0].style.height = pad[0].clientWidth + 'px'
    // })
  }

  public componentDidUpdate() {
    if (this.props.crowdJoin && this.state.clubMethod === "") {
      let jsonContent = this.props.crowdJoin.jsonContent;
      let json;
      let str;
      if (jsonContent != "") {
        json = JSON.parse(jsonContent);
        let gameType = this.props.crowdJoin.gameType;
        let gameName = GameConfig[gameType].name;
        str = gameName + " ";
        Object.keys(json).forEach(item => {
          if (GameConfig[gameType]) {
            let cf = GameConfig[gameType][item];
            if (cf && cf[json[item]]) {
              str += `${cf[json[item]]} `;
            }
          }
        });
      } else {
        str = "暂无玩法";
      }

      this.setState({
        clubMethod: str
      });
    }
  }

  public componentWillUnmount() {
    console.log("componentWillUnmount");
  }

  public componentWillMount() {
    console.warn("app will mount");
  }

  public render() {
    const {
      showJoinRule,
      showHomeJoin,
      clubName,
      clubNumber,
      playMethod,
      clubMethod,
      isAndroid,
      userAmount,
      showAmount
    } = this.state;
    const { crowdJoin } = this.props;

    let infoClass = classnames({
      "is-android": isAndroid,
      "info-header": true
    });

    let isAgent = !!this.props.agentLevel.match("代理");
    return (
      <div className="view-page home-view">
        <div className="home-head">
          <img
            src="img/app/shuaishuai-hy-text.png?v=20181201"
            className={this.state.shuaishuaiCname + " shuaishuai"}
            alt=""
          />
          {/* <img src="img/app/app-head-di.png?v=20181201" {this.props.userInfo.headUrl} alt=""http://tx.haiqq.com/uploads/allimg/150322/021941O30-3.jpg""  className="full pos-abs" alt=""/> */}
          <div className={infoClass}>
            <img src="img/app/head-frame.png?v=20181201" className="head-border" />
            <div className="info-content">
              <div className="head-img-wrapper">
                <img
                  src={this.props.userInfo.headUrl}
                  className="head-img"
                  alt=""
                />
              </div>
              <div className="userinfo-flexbox">
                <div className="mlr-0 text-ellipsis header-first">
                  {this.props.userInfo.nickname}
                </div>
                <div className="mlr-0 header-lftid">
                  ID: {this.props.userInfo.lftid}
                </div>
              </div>
              <div className="diamond-flexbox">
                <img
                  src="img/app/diamond-frame.png?v=20181201"
                  className="diamond-frame"
                />
                <span className="info-diamond-num">
                  <img
                    className="info-diamond"
                    src="img/app/dimond.png?v=20181201"
                    alt=""
                  />
                  <span>
                    {showAmount
                      ? userAmount
                      : this.props.userFinanceInfo.amount}
                  </span>
                </span>
              </div>
            </div>
          </div>
        </div>
        <div className="home-scene">
          {/*<img src="img/app/yun1.png?v=20181201" className="pos-abs yun1" alt="" />*/}
          {/*<img src="img/app/yun2.png?v=20181201" className="pos-abs yun2 " alt="" />*/}
        </div>
        <div className="home-gamepad">
          <GamePad />
        </div>

        <div className="home-join room-swiper-container">
          <div className="swiper-wrapper room-swiper">
            {/* isAgent ? <div className="club-join-container swiper-slide">
              <div className="home-join-content">
                    <img src="img/app/create-pattern-text.png?v=20181201" className="full-width" alt="" />
                    <div className="pure-g">
      
                      <div className="full-width">
                        <a onClick={() => this.setState({ showJoinRule: true })}><img src="img/app/create-pattern-btn.png?v=20181201" className="btn" alt="" /></a>
                      </div>
                    </div>
                  </div>
              
            </div> : null*/}
            <div className="club-join-container swiper-slide">
              { crowdJoin ? (
                <div className="home-join-content">
                  <div className="home-join-wrapper">
                    <div className="full pos-relative">
                      {/* <a href={this.state.cluburl}><img src="img/app/group-btn.png?v=20181201" className="btn" alt=""/></a> */}
                      <img
                        src="img/app/lower-frame.png?v=20181201"
                        alt=""
                        className="lower-frame"
                      />
                      <div className="rapid-join-wrapper">
                        <div className="club-head">
                          <img
                            src="img/app/head-border.png?v=20181201"
                            alt=""
                            className="enter-club"
                          />
                          <img
                            src={crowdJoin.proxyHead}
                            alt=""
                            className="enter-club-head"
                          />
                        </div>
                        <div className="club-details">
                          <span>会长: {crowdJoin.proxyName}</span>
                          <span>俱乐部ID: {crowdJoin.confId}</span>
                          <span className="club-method">
                             {crowdJoin.confName}
                          </span>
                        </div>
                        <a href={crowdJoin.redirectUrl} className="enter-club">
                          <img src="img/app/enter.png?v=20181201" alt="" />
                        </a>
                      </div>
                    </div>
                  </div>
                </div>
              ) : (
                <div className="home-join-content">
                  {/*<img src="img/app/join-line.png?v=20181201" className="full-width" alt="" />*/}
                  <div className="pure-g">
                    {/* <div className="pure-u-1-2">
              <img onClick={() => this.setState({showNumberPad: true})} src="img/app/room-join-btn.png?v=20181201" className="btn" alt=""/>
            </div> */}
                    <div className="full-width">
                      <a onClick={() => this.setState({ showJoinRule: true })}>
                        <img
                          src="img/app/rapid-join-club.png?v=20181201"
                          className="btn"
                          alt=""
                        />
                      </a>
                    </div>
                  </div>
                </div>
              )}
            </div>
            <div className="room-enter-container swiper-slide">
              {/*<img src="img/app/quick-text.png?v=20181201" className="full-width" alt="" />*/}
              <div className="pure-g">
                <div className="full-width">
                  <a onClick={() => this.setState({ showNumberPad: true })}>
                    <img
                      src="img/app/join-room-long.png?v=20181201"
                      className="btn"
                      alt=""
                    />
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="home-nav">
          <img src="img/app/nav-di.png?v=20181201" className="pos-abs di" alt="" />
          <div className="pure-g text-center">
            <div className="pure-u-1-4">
              <a href={this.props.hallPage}>
                <img src="img/app/nav-mall.png?v=20181201" className="btn" alt="" />
              </a>
            </div>
            <div className="pure-u-1-4">
              {/* <a href={this.props.clubUrl}><img src="img/app/lower-club.png?v=20181201" className="btn" alt="" /></a> */}
              <NavLink to="/ClubDetails">
                <img src="img/app/lower-club.png?v=20181201" className="btn" alt="" />
              </NavLink>
            </div>
            <div className="pure-u-1-4">
              <NavLink to="/">
                <img src="img/app/nav-home.png?v=20181201" className="btn" alt="" />
              </NavLink>
            </div>
            <div className="pure-u-1-4">
              <NavLink to="/UserCenter">
                <img src="img/app/nav-my.png?v=20181201" className="btn" alt="" />
              </NavLink>
            </div>
          </div>
        </div>
        {this.props.showCreateGame ? (
          <CreateGameBase currentGame={this.props.currentGame} />
        ) : null}
        {this.state.showNumberPad ? (
          <NumberPad close={() => this.setState({ showNumberPad: false })} />
        ) : null}
        {showJoinRule ? (
          <JoinRuleDialog
            close={() => this.setState({ showJoinRule: false })}
          />
        ) : null}
      </div>
    );
  }
}

//通过react-redux提供的connect方法将我们需要的state中的数据和actions中的方法绑定到props上
const connectedApp = connect(
  mapStateToProps,
  mapDispatchToProps
)(App);
export default connectedApp;
